﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StatisticWord.Question;

namespace StatisticWord.Answer
{
    class Bob : IStatisticWord
    {
        public string IStatisticWord(string str)
        {
            bool isInScope = false;
            int lenght = 0;
            int start = 0;

            List<WordCount> res = new List<WordCount>();
            for (int i = 0; i < str.Length; i++)
            {
                if (char.IsLetterOrDigit(str[i]))
                {
                    if (!isInScope)
                    {
                        isInScope = true;
                        start = i;
                    }
                    lenght++;
                }
                else
                {
                    if (isInScope)
                    {
                        bool isFound = false;
                        string cur = str.Substring(start, lenght);
                        foreach (var curWord in res)
                        {
                            if (curWord.word.ToLower() == cur.ToLower())
                            {
                                curWord.count = curWord.count + 1;
                                isFound = true;
                                break;
                            }
                        }
                        if (!isFound)
                        {
                            res.Add(new WordCount(cur, 1));
                        }
                    }
                    isInScope = false;
                    lenght = 0;
                }
            }


            if (isInScope)
            {
                bool isFound = false;
                string cur = str.Substring(start, lenght);
                foreach (var curWord in res)
                {
                    if (curWord.word.ToLower() == cur.ToLower())
                    {
                        curWord.count = curWord.count + 1;
                        isFound = true;
                        break;
                    }
                }
                if (!isFound)
                {
                    res.Add(new WordCount(cur, 1));
                }
            }
            isInScope = false;
            lenght = 0;

            StringBuilder sb = new StringBuilder();
            foreach (var cur in res)
            {
                sb.Append(string.Format("{0}:{1};", cur.word, cur.count));
            }
            return sb.ToString();
        }
        class WordCount
        {
            public string word;
            public int count;
            public WordCount(string word, int cnt)
            {
                this.word = word;
                this.count = cnt;
            }

        }
    }
}
